package com.xkh.common.util;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileAppender;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.xkh.common.common.constant.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;

/**
 * @author xkh
 * 2020/9/14
 */
@Component
public class FilesUtil {

    public static String filePath;
    private static String fileEcho;

    public static Result templatePackage(String path) {
        String fileName = path + IdUtil.simpleUUID() + ".html";
        File file = FileUtil.touch(fileName);
        FileAppender appender = new FileAppender(file, 16, true);
        appender.append(getTemplateConfig());
        appender.flush();
        return Result.succeed();
    }

    private static String getTemplateConfig() {
        ClassPathResource resource = new ClassPathResource("package/package.txt");
        String text = resource.readStr(Charset.defaultCharset());
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig());
        Template template = engine.getTemplate(text);
        String result = template.render(Dict.create()
                .set("title","标题")
                .set("body","内容")
        );
        return new String(result.getBytes(StandardCharsets.UTF_8));
    }


    @Value("${upload.filePath}")
    public void setFilePath(String path) {
        filePath = path;
    }

    @Value("${upload.echo}")
    public void setFileEcho(String echo) {
        fileEcho = echo;
    }


    public static Result localUpload(MultipartFile file) throws IOException {
        if (ObjectUtil.isNull(FileTypeUtil.getType(file.getInputStream()))) {
            return Result.failure("请勿上传非法文件");
        }
        File dir = new File(filePath);
        //文件夹不存在，则创建
        if (!dir.exists()) {
            dir.mkdir();
        }
        String suffixName = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
        //服务端保存的文件对象
        File serverFile = new File(dir + "/" + UUID.randomUUID() + suffixName);
        //将上传的文件写入到服务端文件内
        try {
            file.transferTo(serverFile);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failure("上传失败");
        }
        return Result.succeed(fileEcho + serverFile.getName());
    }

    public static Result fileAppender(String path) {
        if (!FileUtil.isFile(path)) {
            return Result.failure("文件不存在!");
        }
        File file = FileUtil.file(path);
        FileAppender appender = new FileAppender(file, 16, true);
        appender.append("123");
        appender.append("abc");
        appender.append("xyz");
        appender.flush();
        return Result.succeed();
    }


    /**
     * MultipartFile 转 File
     */
    public static File multipartFileToFile(MultipartFile file) {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            try {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return toFile;
    }

    /**
     * 获取流文件
     *
     * @param ins
     * @param file
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
